package com.baozun.houji.me.fragment

import android.net.Uri
import android.os.Bundle
import android.webkit.ValueCallback
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import com.baozhun.mall.common.base.BaseFragment
import com.baozhun.mall.common.util.Constants
import com.baozhun.mall.common.util.GlideEngine
import com.baozun.houji.me.databinding.FragmentChatBinding
import com.baozun.houji.me.viewmodel.ChatViewModel
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener

/**
 * @Title：客服聊天fragment
 * @Description：
 * @Author：xing.luo
 * @Since：2022/12/16
 * @Version：1.0.0
 */
class ChatFragment : BaseFragment<ChatViewModel, FragmentChatBinding>() {

    companion object {
        fun newInstance(): ChatFragment {
            return ChatFragment()
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        val webSetting = mDataBinding.chatWebView.settings
        webSetting.javaScriptEnabled = true
        webSetting.allowContentAccess = true
        webSetting.databaseEnabled = true
        webSetting.domStorageEnabled = true
        webSetting.cacheMode = WebSettings.LOAD_DEFAULT
        webSetting.useWideViewPort = true
        webSetting.loadWithOverviewMode = true
        mDataBinding.chatWebView.loadUrl(Constants.Url.ON_LINE_CUSTOMER_SERVICE_URL)
        mDataBinding.chatWebView.webChromeClient = ChatWebChromeClient()
    }

    class ChatWebChromeClient : WebChromeClient() {

        override fun onShowFileChooser(webView: WebView?, filePathCallback: ValueCallback<Array<Uri?>?>, fileChooserParams: FileChooserParams?): Boolean {
            PictureSelector.create(webView!!.context)
                .openGallery(if (fileChooserParams?.acceptTypes?.size ?: 0 > 4) SelectMimeType.ofAll() else SelectMimeType.ofImage())
                .setMaxSelectNum(1)
                .setImageEngine(GlideEngine.createGlideEngine())
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: ArrayList<LocalMedia?>?) {
                        result?.let { it ->
                            var filePath = it.map { Uri.parse(it?.path) }
                            filePathCallback.onReceiveValue(filePath.toTypedArray())
                        }
                    }

                    override fun onCancel() {
                        filePathCallback.onReceiveValue(null)
                    }
                })
            return true
        }

    }
}